import { ref, Ref, onMounted, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import { addUser, updateUser } from '@/api/userManage/userManage';
import { getTableData as QueryList } from '@/api/userManage/userManage';
import type { CallBackData } from '@/components/dialog/type.d';
import type { TableListItem, MarkItem } from '@/api/userManage/userManage.d';
import type * as ApiType from '@/api/userManage/userManage.d';
import useSearch from './useSearch';
import useTableData from './useTableData';
import useUser from './useUser';

export default function useCompose() {

    // 当前选中单位
    const currentItem = ref(0);

    const isCreatedMode = computed(()=>{
        return addUserForm.value.code === ''
    })

    // 查询表单
    const { searchForm } = useSearch();

    // 列表数据
    const { columns, data, scroll, total, getTableData } = useTableData(searchForm);

    const { addUserVisibile, addUserForm, userFormRef, markValidList,roleList, handeleAddUserClick,handleEditUser } = useUser();

    const allDataList = ref<{id: number, mobile: string}[]>([]);

    const getAllData = async () => {
        const params = {
            page: 1,
            pageSize: 100000
        }
        const res = await QueryList(params);
        allDataList.value = res.data.list.map(item => ({id: item.id, mobile: item.mobile }))
    }

    // 重置
    const resset = () => {
        searchForm.keyword = undefined;
        searchForm.companyId = '';
        searchForm.page = 1;
        searchForm.pageSize = 10;
        currentItem.value = 0;
        getTableData();
    }

    // 查询
    const search = () => {
        searchForm.page = 1;
        getTableData();
    }

    // 页码操作
    const handleSizeChange = (size: number) => {
        searchForm.page = size;
        getTableData();
    };
    
    // 每页条数操作
    const handlePageSizeChange = (pageSize: number) => {
        searchForm.pageSize = pageSize;
        getTableData();
    };

    // 新增、编辑用户
    const handleUserVisible = async (data: CallBackData) => {
        if (data.status === 'save') {
            const validateRes = await userFormRef.value?.validate();
            if (validateRes !== undefined) return data.done(false)//验证不通过
            data.done(true);//关闭
            if(isCreatedMode.value){//新建
                const res: any = await addUser({
                    userName: String(addUserForm.value.userName),
                    mobile: String(addUserForm.value.mobile),
                    companyId: Number(addUserForm.value.companyId),
                    roleIds: addUserForm.value.roleIds,
                })
                if (res.code === 200 || res.code === 0) {
                    Message.success('新增成功');
                    userFormRef.value.resetFields();
                    addUserVisibile.value = data.flag;
                    getTableData();
                } else {
                    if (res.msg.includes("手机")) {
                        userFormRef.value.setFields({
                            mobile: {
                                status: "error",
                                message: "手机号重复，请修改后添加！"
                            }
                        })
                    }
                }
            }else{//编辑
                const res: any = await updateUser({
                    type: 3,//编辑业务
                    id: String(addUserForm.value.id),
                    userName: String(addUserForm.value.userName),
                    companyId: Number(addUserForm.value.companyId),
                    roleIds: addUserForm.value.roleIds,
                })
                if (res.code === 200 || res.code === 0) {
                    Message.success('编辑成功');
                    userFormRef.value.resetFields();
                    addUserVisibile.value = data.flag;
                    getTableData();
                } else {
                    Message.success('编辑保存失败，请重试');
                }
            }
        } else if (data.status === 'clear') {
            userFormRef.value.resetFields();
            addUserVisibile.value = data.flag;
        }
    }

    // 修改用户状态
    const handleUserStatus = async (item: TableListItem) => {
        const params = {
            type: 1,
            id: String(item.id),
            status: item.status
        }
        const res = await updateUser(params);
        // @ts-ignore
        if (res?.code === 200) {
            Message.success('修改成功');
            getTableData();
        }
    };

    // 点击单位过滤表格数据
    const handleShowUser = (item: MarkItem, e: MouseEvent) => {
        e.stopPropagation();
        if (currentItem.value === item.id) {
            searchForm.companyId = '';
            currentItem.value = 0;
            searchForm.page = 1;
            searchForm.pageSize = 10;
        } else {
            currentItem.value = item.id;
            searchForm.companyId = item.id + '';
            searchForm.page = 1;
            searchForm.pageSize = 10;
        }
        getTableData();
    }

    // 手机号输入处理
    // const handleMobileChange = (value: string, ev: Event) => {
    //     if (allDataList.value.find(item => item.mobile === value)) {
    //         userFormRef.value.setFields({
    //             mobile: {
    //                 status: 'error',
    //                 message: '手机号已存在，请重新输入'
    //             }
    //         })
    //     } 
    // }

    const getMobile = (value: string | undefined, callback: (error?: string) => void) => {
        return new Promise(resolve => {
            if (value === 'admin') {
                callback('');
            }
            resolve(value);
        })
    }

    onMounted(() => getAllData());

    return {
        searchForm,
        resset,
        search,
        columns,
        data,
        scroll,
        total,
        getTableData,
        handleSizeChange,
        handlePageSizeChange,
        addUserVisibile,
        addUserForm,
        userFormRef,
        markValidList,
        roleList,
        handeleAddUserClick,
        handleEditUser,
        handleUserVisible,
        handleUserStatus,
        currentItem,
        handleShowUser,
    }
}